import React, {useCallback, useEffect, useRef, useState} from 'react';
import {Alert, DeviceEventEmitter, Image, ScrollView, StyleSheet, Text, View} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Container from '../../components/Container';
import Images from '../../images/images';
import TouchableView from '../../components/touchableView';
import LinkButton from '../../components/linkButton';
import {useAppStore} from '../../store/useAppStore';
import BleUtil from '../../utils/bleUtil';
import {useLoading} from '../../components/loading/useLoading';
import {useToast} from '../../components/toast/useToast';
import store from 'react-native-simple-store';
import {EventName} from '../../utils/common';
import Battery from '../../components/battery';
import {useDialog} from '../../components/dialog/useDialog';
import {useModal} from '../../components/useModal';
import DebugBle from './debugBle';
import {setGpsInfoCmd} from '../../utils/bleCmd';

const Detail = ()=>{
    const navigation = useNavigation()
    const  loading = useLoading()
    const toast = useToast()
    const dialog = useDialog()
    const modal = useModal()
    const route = useRoute()
    const {appState:{currentDevice,bluetoothEnable,battery,debugMode,location},updateAppState }= useAppStore()
    const {data} = route.params
    const isConnect = currentDevice && (currentDevice.id === data.id )
    const [name,setName] = useState(data.localName ?? data.name)
    const storeKey = `device_${data.id}`
    const [count,setCount] = useState({
        tmp:0,contact:0
    })
    const countRef = useRef(0)


    useEffect(()=>{
        getDeviceInfo()
        getCount()
        const notifyListener = BleUtil.addNotifyListener((info,cmd)=>{
            console.log('notify:',cmd,info);
            if(info.includes('battery')){
                const battery = info.replace('battery:','')
                console.log('电量',battery);
                if(parseInt(battery)){
                    updateAppState({battery})
                }
            }
        })


        const countListener = DeviceEventEmitter.addListener(EventName.countUpdate,()=>{
            getCount()
        })

        return ()=>{
            notifyListener.remove()
            countListener.remove()
        }
    },[])

    const getDeviceInfo = ()=>{
        BleUtil.isPeripheralConnected(data.id).then(isConnected=>{
            console.log('是否连接',isConnected);
            if(isConnected){
                updateAppState({
                    currentDevice: data
                })
                getSysInfo()

            }else{
                if(currentDevice && currentDevice.id === data.id){
                    updateAppState({
                        currentDevice:null,
                        battery:0
                    })
                }
            }
        })



    }

    const getCount = ()=>{
        store.get(storeKey).then(res=>{
            if(res){
                // console.log('-------',res);
                const {message,contact} = res
                setCount(prevState => {
                    return {...prevState,
                        tmp:message ? message.list.length : 0,
                        contact:contact ? contact.list.length : 0
                    }
                })
            }
        })

    }

    const getSysInfo = ()=>{
        //防止发送指令执之前就已经断开了链接
        if(!BleUtil.writeServiceUUID || !BleUtil.writeCharacteristicUUID) return
        sendCmd('getSysInfo\r\n')

    }

    const setGpsInfo = ()=>{
        if(!location) return
        let cmd = setGpsInfoCmd(location)
        // console.log(cmd);
        sendCmd(cmd)
    }

    const sendCmd = (cmd)=>{
        if(!isTabe01()){
            BleUtil.writeWithoutResponse(data.id,cmd).then(()=>{
                console.log(cmd);
            }).catch(error=>{
                console.log('write error:',error);
            })
        }else{
            BleUtil.write(data.id,cmd).then(()=>{
                console.log(cmd);
            }).catch(error=>{
                console.log('write error:',error);
            })
        }

    }


    const onConnect = ()=>{
        if(!bluetoothEnable){
            toast.show('请打开蓝牙')
            return
        }

        //如果有连接设备，先断开连接
        console.log('currentDevice',currentDevice);
        if(currentDevice){
            dialog.alert({
                title:'连接新设备需要先断开当前连接',
                button: [
                    {
                        text: '确定',
                        onPress: () => {
                            loading.show('连接中')
                            BleUtil.disconnect(currentDevice.id).then(res=>{
                                console.log('断开连接了：',res)
                                updateAppState({currentDevice: null,battery:0})
                                connect()
                            })
                        },
                        pressHide: true,
                        tag: 'confirm',
                        onClose: false
                    },
                    {
                        text: '取消',
                        onPress: () => {

                        },
                        pressHide: true,
                        tag: 'cancel',
                        onClose: false
                    },
                ]
            })

        }else{
            loading.show('连接中')
            connect()
        }

    }

    const connect = ()=>{

        BleUtil.connectAndPrepare(data.id).then((info)=>{
            updateAppState({
                currentDevice: data
            })
            setTimeout(()=>{
                getSysInfo()
                setGpsInfo()
            },1000)
            loading.hide()
        }).catch(error=>{
            loading.hide()
            let message = error.error === 'timeout' ? '连接超时' : '连接失败'
            toast.show(message)
        })

        /*
        BleUtil.connect(data.id,(info)=>{
            if(info.error){
                loading.hide()
                let message = info.error === 'timeout' ? '连接超时' : '连接失败'
                toast.show(message)
                return
            }
            console.log('info:',info)
            updateAppState({
                currentDevice: {...data,...info}
            })
            prepare()
            loading.hide()
        })
        */
    }

    const disconnect = ()=>{
        loading.show()
        BleUtil.disconnect(data.id).then(()=>{
            updateAppState({
                currentDevice: null,battery:0
            })

            loading.hide()
        }).catch(err=>{
            updateAppState({
                currentDevice: null
            })
            loading.hide()
        })
    }

    const isTabe01 = useCallback(()=>{
        return data.name.includes('TABE01')
    },[])

    let imageSource = Images.device02
    if(isTabe01()){
        imageSource = Images.device01
    }

    return (
        <Container >
            <ScrollView
                contentContainerStyle={{padding:screen.PIXEL_30}}
            >
                <View style={styles.topView}>
                    <View>
                        <Image source={imageSource} resizeMode={'contain'} style={{width:screen.PIXEL_250,height:screen.PIXEL_350}}/>
                        <TouchableView
                            style={StyleSheet.absoluteFill}
                            onPress={()=> {
                                //连点七下出现调试彩蛋
                                if (countRef.current > 7) {
                                    // setDebug(true)
                                    updateAppState({debugMode: true})
                                }else{
                                    countRef.current += 1
                                    if(countRef.current == 7){
                                        toast.show('即将进入调试模式')
                                    }
                                }
                            }}
                            >

                        </TouchableView>
                    </View>

                    <TouchableView
                        style={[styles.rowCenter,{marginTop:screen.PIXEL_40,paddingHorizontal:20}]}
                        onPress={()=>{

                            navigation.navigate('DeviceName',{data:{...data,localName:name},callback:(newName)=>{
                                setName(newName)
                            }})
                        }}

                    >
                        <Text style={{color:'#333',fontSize:16,fontWeight:'bold'}}>{name}</Text>
                        <Image source={Images.edit} style={{width:screen.PIXEL_24,height:screen.PIXEL_24,marginLeft:5}}/>
                    </TouchableView>
                    <View style={[styles.rowCenter,{marginTop:screen.PIXEL_20}]}>
                        <Text style={{color:'#333',fontSize:16,fontWeight:'bold'}}>状态:</Text>
                        <Image source={isConnect ? Images.connect : Images.disconnect} style={{width:screen.PIXEL_24,height:screen.PIXEL_24}}/>
                        <Text style={{color:'#333',fontSize:16,fontWeight:'bold'}}>{isConnect ? '已连接' : '未连接'}</Text>
                    </View>

                    <TouchableView
                        style={{position:'absolute',top:0,right:0,padding:screen.PIXEL_30}}
                        onPress={()=>{
                            navigation.navigate('DeviceInfo',{data})
                        }}
                    >
                        <Image source={Images.detail} style={{width:screen.PIXEL_30,height:screen.PIXEL_30}}/>
                    </TouchableView>

                    {
                        isConnect && battery ? (
                            <Battery
                                style={{position:'absolute',top:10,left:10}}
                                battery={battery}
                            />
                        ) : null
                    }


                    <LinkButton
                        style={{marginTop:screen.PIXEL_50}}
                        title={isConnect ?  '断开连接' : '连接设备'}
                        onPress={()=>isConnect ? disconnect() : onConnect()}
                    />
                </View>

                <TouchableView
                    style={styles.moduleView}
                    onPress={()=>{
                        if(isTabe01()){
                            toast.show('设备不支持该功能')
                            return
                        }
                        if(isConnect){
                            navigation.navigate('Message',{data})
                        }else{
                            toast.show('请先连接设备')
                        }
                    }}
                >
                    <Image source={Images.message} style={{width:screen.PIXEL_30,height:screen.PIXEL_30}} resizeMode={'contain'}/>
                    <Text style={{color:'#333',fontSize:15,marginLeft:screen.PIXEL_16}}>短信模板 ({count.tmp}/5)</Text>
                </TouchableView>

                <TouchableView
                    style={styles.moduleView}
                    onPress={()=>{
                        if(isTabe01()){
                            toast.show('设备不支持该功能')
                            return
                        }
                        if(isConnect){
                            navigation.navigate('Contact',{data})
                        }else{
                            toast.show('请先连接设备')
                        }
                    }}
                >
                    <Image source={Images.contact} style={{width:screen.PIXEL_30,height:screen.PIXEL_30}} resizeMode={'contain'}/>
                    <Text style={{color:'#333',fontSize:15,marginLeft:screen.PIXEL_16}}>联系人 ({count.contact}/5)</Text>
                </TouchableView>

                {
                    debugMode && (
                        <TouchableView
                            style={styles.moduleView}
                            onPress={()=>{
                                if(isTabe01()){
                                    toast.show('设备不支持该功能')
                                    return
                                }
                                if(isConnect){
                                    modal.showContent(
                                        <DebugBle
                                            data={data}
                                            count={count}
                                            onClose={()=>{
                                                modal.close()
                                            }}
                                            onCloseDebug={()=>{
                                                updateAppState({debugMode: false})
                                                countRef.current = 0
                                                modal.close()
                                            }}
                                        />
                                    )
                                }else{
                                    toast.show('请先连接设备')
                                }

                            }}
                        >
                            <Image source={Images.custom_service} style={{width:screen.PIXEL_30,height:screen.PIXEL_30}} resizeMode={'contain'}/>
                            <Text style={{color:'#333',fontSize:15,marginLeft:screen.PIXEL_16}}>进入调试</Text>
                        </TouchableView>
                    )
                }


            </ScrollView>

        </Container>
    )
}
export default Detail
const styles = StyleSheet.create({
    container:{
        flex: 1, justifyContent: 'center', alignItems: 'center'
    },
    topView:{
        backgroundColor:'#fff',borderRadius:screen.PIXEL_20,alignItems: 'center',
        paddingVertical:screen.PIXEL_50
    },
    rowCenter:{
        flexDirection:'row',alignItems:"center",
    },
    moduleView:{
        backgroundColor:'#fff',borderRadius:screen.PIXEL_20,height:screen.PIXEL_88,
        paddingLeft:screen.PIXEL_30,flexDirection:'row',alignItems:"center",
        marginTop:screen.PIXEL_40
    }
})
